package com.jcj.jcjsharding.datasource;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.jcj.jcjsharding.engine.ShardingContext;
import com.jcj.jcjsharding.engine.ShardingResult;
import com.jcj.jcjsharding.config.ShardingProperites;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 抽象的数据源
 */
@Slf4j
public class ShardingDataSource extends AbstractRoutingDataSource {

    public ShardingDataSource(ShardingProperites properties) {
        Map<Object, Object> dataSourceMap = new LinkedHashMap<>();
        properties.getDatasources().forEach((k, v) -> {
            try {
                //采用durid创建数据源
                dataSourceMap.put(k, DruidDataSourceFactory.createDataSource(v));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });

        //设置map到目标数据源
        setTargetDataSources(dataSourceMap);

        //添加默认的数据源 传入第一个vaLue
        setDefaultTargetDataSource(dataSourceMap.values().iterator().next());
    }

    @Override
    protected Object determineCurrentLookupKey() {
        //选择哪个数据源
        //通过返回的key，从map获取DataSource。
        ShardingResult result = ShardingContext.get();
        Object key = result == null ? null : result.getTargetDataSourceName();
        log.info("选择采用哪个数据库，key:{}", key);
        return key;
    }
}
